const { staff_collection } = require('../config')
const pick = require('lodash/pick')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
exports.main = async (event, context) => {
    const data = event;
    var filter = { status: _.neq('离职'), position: "全职装维" };
    data.staffName && (filter.name = new RegExp(data.staffName, 'i'))
    data.region && (filter.region = new RegExp(data.region, 'i'))
    data.grid && (filter.grid = new RegExp(data.grid, 'i'))
    // 如果 data.minArea 存在且不为空，则添加筛选条件
    if (data.minArea && data.minArea !== '') {
        filter.$and = filter.$and || []; // 确保 $and 条件存在
        filter.$and.push({ area: { $gt: Number(data.minArea) } }); // 添加筛选条件
    }
    // 如果 data.maxArea 存在且不为空，则添加筛选条件
    if (data.maxArea && data.maxArea !== '') {
        filter.$and = filter.$and || []; // 确保 $and 条件存在
        filter.$and.push({ area: { $lt: Number(data.maxArea) } }); // 添加筛选条件
    }
    const count = await db.collection(staff_collection).where(filter).count();
    let lists, page, pageSize;
    if (data.hasOwnProperty('page') && data.pageSize) {
        page = data.page;
        pageSize = data.pageSize;
        lists = await db.collection(staff_collection).where(filter).orderBy('area', 'desc').skip(page * pageSize).limit(pageSize).get();
    } else {
        lists = await db.collection(staff_collection).where(filter).orderBy('area', 'desc').limit(1000).get();
    }
    let returnData = []
    if (lists.data && lists.data.length) {
        returnData = lists.data.map(i => {
            const item = pick(i, ['name', 'region', 'grid', 'userCount', 'perimeter', 'area', 'centersDistance', 'toRegionCentersDistance', 'obdTownCount', 'gridOffset', 'regionOffset']);
            return item;
        })
    }
    if (data.hasOwnProperty('page') && data.pageSize) {
        return { data: returnData, page, pageSize, total: count.total };
    } else {
        return { data: returnData, total: count.total };
    }
}
